package kr.saeildamil.androidforstudy2.ch2930;

import java.util.Calendar;

import kr.saeildamil.androidforstudy2.R;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.SystemClock;
import android.view.View;
import android.widget.Toast;

public class AlarmTest extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.ch29_alarmtest);
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		IntentFilter alarmFilter = new IntentFilter("kr.saeildamil.androidforstudy2.ch29.ALARM");
		registerReceiver(AlarmReceiver, alarmFilter);
		
		IntentFilter tenMinuteFilter = new IntentFilter("kr.saeildamil.androidforstudy2.ch29.FIVESECONDS");
		registerReceiver(FiveSeconds, tenMinuteFilter);
	}
	
	@Override
	protected void onPause() {
		super.onPause();
		unregisterReceiver(AlarmReceiver);
		unregisterReceiver(FiveSeconds);
	}
	
	public void mOnClick(View v){
		AlarmManager alarm = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
		Intent intent;
		PendingIntent sender;
		
		switch (v.getId()) {
		case R.id.onetime:
			intent = new Intent("kr.saeildamil.androidforstudy2.ch29.ALARM");
			sender = PendingIntent.getBroadcast(this, 0, intent, 0);
			
			// 10 seconds!
			Calendar calendar = Calendar.getInstance();
			calendar.setTimeInMillis(System.currentTimeMillis());
			calendar.add(Calendar.SECOND, 5);
			
			// Register Alarm;
			alarm.set(AlarmManager.RTC, calendar.getTimeInMillis(), sender);
			break;
		case R.id.repeat:
			break;
		case R.id.stop:
			intent = new Intent("kr.saeildamil.androidforstudy2.ch29.FIVESECONDS");
			sender =PendingIntent.getBroadcast(this, 0, intent, 0);
			if(v.getId() == R.id.repeat){
				alarm.setRepeating(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime(), 5000, sender);
			}else{
				alarm.cancel(sender);
			}
			break;
		}
	}
	
	BroadcastReceiver AlarmReceiver = new BroadcastReceiver() {
		
		@Override
		public void onReceive(Context context, Intent intent) {
			Toast.makeText(context, "It's time to...!", Toast.LENGTH_SHORT).show();
		}
	};
	
	BroadcastReceiver FiveSeconds = new BroadcastReceiver() {
		
		@Override
		public void onReceive(Context context, Intent intent) {
			Toast.makeText(context, "You just passed 5 seconds", Toast.LENGTH_SHORT).show();
		}
	};
}
